package indv.Cning.cfengsecuritydemo.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.PermitAll;

/**
 * @author Cfeng
 * @date 2022/7/22
 */

@RestController
public class UserController {

    @RequestMapping("/main")
    public ModelAndView toIndex() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @Secured({"ROLE_admin"})  //String[]  权限数组,角色可以转为权限
    @RequestMapping("/admin")
    public String toAdmin() {
        Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
        return "welcome ," + currentUser.getPrincipal().toString() + ", 只能admin访问的";
    }

    @PreAuthorize("hasAuthority('article_write') AND hasAuthority('article_read')")  //可以直接使用Spel表达式，使用hasRole等,单引号，使用AND OR连接
    @RequestMapping("/all")
    public String toUser() {
        return "两种权限都有才可以访问";
    }

    @PermitAll
    @RequestMapping("/welcome")
    public String toAccess() {
        return "欢迎，你们不登陆也能访问，都可以访问";
    }

    @RequestMapping("/user")
    public String userAccess() {
        return SecurityContextHolder.getContext().getAuthentication().getName()  + ", 只能User访问";
    }

}
